package ink.xiaobaibai.serviceOxy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiniu.common.QiniuException;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import ink.xiaobaibai.common.ClientInfo;
import ink.xiaobaibai.common.DeviceType;
import ink.xiaobaibai.common.QiNiuCommon;
import ink.xiaobaibai.entity.*;
import ink.xiaobaibai.enumOxy.MonthlyfeeOrderStatus;
import ink.xiaobaibai.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 短信服务
 * @author: 小白白
 * @create: 2021-08-21
 **/

@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    private IMonthlyfeeOrderService monthlyOrderService;

    @Autowired
    private ILogisticsService logisticsService;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IOzoneDeviceService ozoneDeviceService;

    @Autowired
    private IOxygenDeviceService oxygenDeviceService;

    @Autowired
    private IMonthlyfeeDeviceService monthlyfeeDeviceService;

    @Autowired
    private IMonthlyOxygenDeviceService monthlyOxygenDeviceService;

    @Autowired
    private IBuyOzoneDeviceService buyOzoneDeviceService;

    @Autowired
    private IBuyOxygenDeviceService buyOxygenDeviceService;

    @Autowired
    private IFreeOzoneDeviceService freeOzoneDeviceService;

    @Autowired
    private IFreeOxygenDeviceService freeOxygenDeviceService;

    @Autowired
    private IMonthlyfeeOrderService monthlyfeeOrderService;

    @Autowired
    private IMonthlyfeeDepositService depositService;

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    private static Auth auth = Auth.create(QiNiuCommon.accessKey, QiNiuCommon.secretKey);
    private static SmsManager smsManager = new SmsManager(auth);

    @Override
    public void deviceFaultSms(String deviceCode, DeviceType deviceType, Boolean isOxy) {
        this.executorService.execute(() -> {
            // 查询负责人,然后发送短信
            if (deviceType == DeviceType.ONEPAY) {
                if (isOxy) {
                    QueryWrapper<OxygenDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    OxygenDevice oxygenDevice = this.oxygenDeviceService.getOne(q1);
                    if (oxygenDevice == null) {
                        return;
                    }
                    Integer adminUserId = oxygenDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                } else {
                    QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    OzoneDevice ozoneDevice = this.ozoneDeviceService.getOne(q1);
                    if (ozoneDevice == null) {
                        return;
                    }
                    Integer adminUserId = ozoneDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                }
            } else if (deviceType == DeviceType.MON) {
                if (isOxy) {
                    QueryWrapper<MonthlyOxygenDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    MonthlyOxygenDevice monthlyOxygenDevice = this.monthlyOxygenDeviceService.getOne(q1);
                    if (monthlyOxygenDevice == null) {
                        return;
                    }
                    Integer adminUserId = monthlyOxygenDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                } else {
                    QueryWrapper<MonthlyfeeDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    MonthlyfeeDevice monthlyfeeDevice = this.monthlyfeeDeviceService.getOne(q1);
                    if (monthlyfeeDevice == null) {
                        return;
                    }
                    Integer adminUserId = monthlyfeeDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                }
            } else if (deviceType == DeviceType.BUY) {
                if (isOxy) {
                    QueryWrapper<BuyOxygenDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    BuyOxygenDevice buyOxygenDevice = this.buyOxygenDeviceService.getOne(q1);
                    if (buyOxygenDevice == null) {
                        return;
                    }
                    Integer adminUserId = buyOxygenDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                } else {
                    QueryWrapper<BuyOzoneDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    BuyOzoneDevice buyOzoneDevice = this.buyOzoneDeviceService.getOne(q1);
                    if (buyOzoneDevice == null) {
                        return;
                    }
                    Integer adminUserId = buyOzoneDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                }
            } else if (deviceType == DeviceType.FREE) {
                if (isOxy) {
                    QueryWrapper<FreeOxygenDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    FreeOxygenDevice freeOxygenDevice = this.freeOxygenDeviceService.getOne(q1);
                    if (freeOxygenDevice == null) {
                        return;
                    }
                    Integer adminUserId = freeOxygenDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                } else {
                    QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
                    q1.select("admin_user_id");
                    q1.eq("device_code", deviceCode);
                    FreeOzoneDevice freeOzoneDevice = this.freeOzoneDeviceService.getOne(q1);
                    if (freeOzoneDevice == null) {
                        return;
                    }
                    Integer adminUserId = freeOzoneDevice.getAdminUserId();
                    this.deviceFaultSms(adminUserId, deviceCode, deviceType);
                }
            } else {
                // Nothing happened
            }
        });
    }

    private void deviceFaultSms(Integer adminUserId, String deviceCode, DeviceType deviceType) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        /**
         * [adminUserName]负责人你好,你旗下负责的机器:
         * 机器码为[deviceCode]的机器网络连接异常([type]业务),敬请注意。
         */
        AdminUser adminUser = this.adminUserService.getNameAndPhone(adminUserId);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("adminName", adminUser.getUserName());
        paramsMap.put("type", deviceType.type);
        paramsMap.put("code", deviceCode);
        try {
            smsManager.sendMessage("1429769449283530752", new String[]{adminUser.getUserPhone()}, paramsMap);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void trusteeshipSms(Integer userId, Integer deviceId) {
        // 月费托管提醒
        QueryWrapper<MonthlyfeeOrder> q1 = new QueryWrapper<>();
        q1.select("admin_user_id", "logistics_id");
        q1.eq("user_id", userId);
        q1.eq("device_id", deviceId);
        q1.eq("status", MonthlyfeeOrderStatus.INUSE.getStatus());
        MonthlyfeeOrder monthlyfeeOrder = this.monthlyOrderService.getOne(q1);
        if (monthlyfeeOrder == null) {
            return;
        }
        Integer adminUserId = monthlyfeeOrder.getAdminUserId();
        Integer logisticsId = monthlyfeeOrder.getLogisticsId();
        /**
         * [adminUserName]负责人你好,你旗下负责的客户:
         * 用户id:[userId],姓名:[userName],电话:[userPhone],其对id为[deviceId]的机器开启了托管,敬请注意。
         */
        AdminUser adminUser = this.adminUserService.getNameAndPhone(adminUserId);
        Logistics logistics = this.logisticsService.getById(logisticsId);
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("id", deviceId.toString())
                .put("name", logistics.getName());
        // 七牛短信不支持电话 只支持400开头电话
//                .put("phone", logistics.getPhone());
        try {
            smsManager.sendMessage("1437055382236184576", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void depositSms(ClientInfo clientInfo) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        AdminUser adminUser = this.adminUserService.getNameAndPhone(clientInfo.getAdminUserId());
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("clientName", clientInfo.getName())
                .put("phone", clientInfo.getPhone())
                .put("address", clientInfo.getAddress());
        try {
            smsManager.sendMessage("1429767765593440256", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void newMonthly(ClientInfo clientInfo) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        AdminUser adminUser = this.adminUserService.getNameAndPhone(clientInfo.getAdminUserId());
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("clientName", clientInfo.getName())
                .put("phone", clientInfo.getPhone())
                .put("address", clientInfo.getAddress());
        try {
            smsManager.sendMessage("1429767681157906432", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addDay(Integer depId) {
        AdminUser adminUser = null;
        if (depId == -1) {
            // 管理员
            adminUser = this.adminUserService.getById(1);
        } else {
            // 经理
            adminUser = this.adminUserService.getAgentIdByDepId(depId);
        }
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName());
        try {
            smsManager.sendMessage("1429768207102652416", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void monDueReminder(String orderId, Integer adminUserId, Integer clientUserId, Integer deviceId, Date expireTime) {
        int day = (int) ((System.currentTimeMillis() - expireTime.getTime()) / (1000 * 3600 * 24));
        AdminUser adminUser = this.adminUserService.getById(adminUserId);
        MonthlyfeeOrder order = this.monthlyfeeOrderService.getById(orderId);
        Integer logisticsId = order.getLogisticsId();
        Logistics logistics = this.logisticsService.getById(logisticsId);
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("day", String.valueOf(day))
                .put("clientName", logistics.getName())
                .put("phone", logistics.getPhone())
                .put("address", logistics.getAddress());
        try {
            smsManager.sendMessage("1429768672863334400", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        QueryWrapper<MonthlyfeeDevice> q1 = new QueryWrapper<>();
        q1.select("device_code");
        q1.eq("id", deviceId);
        String deviceCode = this.monthlyfeeDeviceService.getOne(q1).getDeviceCode();
        // 顾客的
        paramsMap = new ParamsMap()
                .put("clientName", logistics.getName())
                .put("code", deviceCode);
        try {
            smsManager.sendMessage("1429768892292542464", new String[]{logistics.getPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void buySms(ClientInfo clientInfo) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        AdminUser adminUser = this.adminUserService.getNameAndPhone(clientInfo.getAdminUserId());
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("clientName", clientInfo.getName())
                .put("phone", clientInfo.getPhone())
                .put("address", clientInfo.getAddress());
        try {
            smsManager.sendMessage("1429767840507899904", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void returnDeposit(String orderId) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        MonthlyfeeDeposit deposit = this.depositService.getById(orderId);
        AdminUser adminUser = this.adminUserService.getNameAndPhone(deposit.getAdminUserId());
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("clientName", deposit.getClientUserName())
                .put("phone", deposit.getClientUserPhone())
                .put("address", deposit.getClientUserAddress());
        try {
            smsManager.sendMessage("1429768286752489472", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void faultUser(String deviceCode, String msg) {
        QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
        q1.select("admin_user_id");
        q1.eq("device_code", deviceCode);
        OzoneDevice ozoneDevice = this.ozoneDeviceService.getOne(q1);
        Integer adminUserId = ozoneDevice.getAdminUserId();
        AdminUser adminUser = this.adminUserService.getNameAndPhone(adminUserId);
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("msg", msg);
        try {
            smsManager.sendMessage("1429769720323649536", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void oaSms(Integer adminUserId, String msg) {
        // TODO 生产时记得去除
        if (true) {
            return;
        }
        AdminUser adminUser = this.adminUserService.getNameAndPhone(adminUserId);
        ParamsMap paramsMap = new ParamsMap()
                .put("adminName", adminUser.getUserName())
                .put("type", msg == null ? "未知" : msg);
        try {
            smsManager.sendMessage("1437055252078542848", new String[]{adminUser.getUserPhone()}, paramsMap.map);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    static class ParamsMap {

        private Map<String, String> map = new HashMap<>();

        public ParamsMap put(String key, String value) {
            this.map.put(key, value);
            return this;
        }

        public Map<String, String> build() {
            return this.map;
        }

    }

}
